<template>
  <div class="pd_container">
    <div class="top_btn">
      <el-button class="btn-active" size="mini" @click="generate"><img src="@/assets/img/u576.svg">生成场景</el-button>
      <el-button class="btn-active g1" size="mini" @click="generate"><img src="@/assets/img/u576.svg">保存草稿</el-button>
    </div>
    <div class="body">
      <div class="tools">
        <div class="item">
          <div class="head">
            <img src="@/assets/img/arrow.svg">
            工具
          </div>
          <div class="item-box">
            <div class="item-icon" :class="{active: toolActive == 'a1'}" @click="chooseTool('a1')">
              <img src="/ic/arrow_.png">
            </div>
            <div class="item-icon" :class="{active: toolActive == 'a2'}" @click="chooseTool('a2')">
              <img style="height: 26px" src="/ic/wenzi.png">
            </div>
          </div>
        </div>
        <div class="item">
          <div class="head">
            <img src="@/assets/img/arrow.svg">
            第一层级样式
          </div>
          <div class="item-icon" :class="{active: toolActive == 't1'}" @click="chooseTool('t1')">
            <img src="/ic/t1.png">
          </div>
        </div>
        <div class="item">
          <div class="head">
            <img src="@/assets/img/arrow.svg">
            第二层级样式
          </div>
          <div class="item-box">
            <div class="item-icon" :class="{active: toolActive == 't2-1'}" @click="chooseTool('t2-1')">
              <img src="/ic/t2-1.png">
              任务
            </div>
            <div class="item-icon" :class="{active: toolActive == 't2-2'}" @click="chooseTool('t2-2')">
              <img src="/ic/t2-2.png">
              发送
            </div>
            <div class="item-icon" :class="{active: toolActive == 't2-3'}" @click="chooseTool('t2-3')">
              <img src="/ic/t2-3.png">
              等待
            </div>
          </div>
        </div>
      </div>
      <div id="_5mf79t1q" class="draw">
        <!-- <div style="width: 2000px;height: 1200px;" /> -->
      </div>
      <div class="allocation">
        <el-tabs v-model="activeName" class="ac1" @tab-click="handleClick">
          <el-tab-pane label="内容设置" name="first">
            <div v-if="Object.keys(nodes).length > 0" class="st1 content1">
              <div>
                <span class="label">标题:</span><input :value="nodes.attrs.data.txt" class="input" @input="(e)=>inputWord(e,'attrs.data.txt')">
              </div>
              <template v-if="nodes.attrs && nodes.attrs.name == 'node2'">
                <div>
                  <span class="label">执行内容:</span><input :value="nodes.attrs.data.remark" class="input" @input="(e)=>inputWord(e,'attrs.data.remark')">
                </div>
                <div>
                  <span class="label">节点类型:</span>
                  <!-- <input :value="nodes.data.nodeType" class="input" @input="(e)=>inputWord(e,'data.nodeType')"> -->
                  <el-select
                    v-model="nodes.attrs.data.nodeType"
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="(item,idx) in dict"
                      :key="idx"
                      :label="item.dictLabel"
                      :value="item.dictValue"
                    />
                  </el-select>
                </div>
                <div>
                  <span class="label">类型:</span>
                  <el-select
                    v-model="dType"
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      label="设备"
                      value="1"
                    />
                    <el-option
                      label="仪器"
                      value="2"
                    />
                  </el-select>
                </div>
                <div v-if="dType == '1'">
                  <span class="label">设备:</span>
                  <!-- <input :value="nodes.data.instrumentId" class="input" @input="(e)=>inputWord(e,'data.instrumentId')"> -->
                  <el-select
                    v-model="nodes.attrs.data.deviceId"
                    placeholder="请选择"
                    style="width: 100%"
                    @change="(e)=> { delete nodes.attrs.data.instrumentId; getOrder(e) }"
                  >
                    <el-option
                      v-for="(item,idx) in devicelist"
                      :key="idx"
                      :label="item.deviceName"
                      :value="item.deviceId"
                    />
                  </el-select>
                </div>
                <div v-if="dType == '2'">
                  <span class="label">仪器:</span>
                  <!-- <input :value="nodes.data.deviceId" class="input" @input="(e)=>inputWord(e,'data.deviceId')"> -->
                  <el-select
                    v-model="nodes.attrs.data.instrumentId"
                    placeholder="请选择"
                    style="width: 100%"
                    @change="(e)=> { delete nodes.attrs.data.deviceId; getOrder(e) }"
                  >
                    <el-option
                      v-for="(item,idx) in machinelist"
                      :key="idx"
                      :label="item.instrumentName"
                      :value="item.instrumentId"
                    />
                  </el-select>
                </div>
                <div>
                  <span class="label">循环次数:</span><input :value="nodes.attrs.data.nodeData" class="input" @input="(e)=>inputWord(e,'attrs.data.nodeData')">
                </div>
                <!-- <div>
                  <span class="label">操作类型:</span><input :value="nodes.attrs.data.dictCode" class="input" @input="(e)=>inputWord(e,'attrs.data.dictCode')">
                </div> -->
                <!-- <div>
                  <span class="label">指令:</span><input :value="nodes.attrs.data.comdId" class="input" @input="(e)=>inputWord(e,'attrs.data.comdId')">
                </div> -->
                <div>
                  <span class="label">指令:</span>
                  <el-select
                    v-model="nodes.attrs.data.comdId"
                    placeholder="请选择"
                    style="width: 100%"
                  >
                    <el-option
                      v-for="(item,idx) in instructionDict"
                      :key="idx"
                      :label="item.comdName"
                      :value="item.comdId"
                    />
                  </el-select>
                </div>
                <!-- <div>
                  <span class="label">指令值:</span><input :value="nodes.attrs.data.comdData" class="input" @input="(e)=>inputWord(e,'attrs.data.comdData')">
                </div> -->
              </template>
              <!-- <div style="margin-top: 20px;">
                <span class="btn" @click="openCinfig">配置</span>
              </div> -->
            </div>
          </el-tab-pane>
          <el-tab-pane label="参数配置" name="second">
            <div class="card st1">
              <template v-if="nodes.attrs && nodes.attrs.name == 'node2'">
                <template v-if="nodes.attrs.data.sceneChildNodeInfoList">
                  <template v-for="(item1,idx) in nodes.attrs.data.sceneChildNodeInfoList">
                    <div :key="idx" class="content1 ccon">
                      <div>
                        <span class="label">参数:</span>
                        <el-select
                          v-model="nodes.attrs.data.sceneChildNodeInfoList[idx].parmId"
                          placeholder="请选择"
                          style="width: 100%"
                          @change="(e)=> { item1.parmName = parameterOptions.find(it=>it.parmId == e).parmName; nodes = {...nodes} }"
                        >
                          <el-option
                            v-for="(item,idx1) in parameterOptions"
                            :key="idx1"
                            :label="item.parmName"
                            :value="item.parmId"
                          />
                        </el-select>
                      </div>
                      <div style="margin-top: 6px;">
                        <span class="label">参数值:</span><input v-model="nodes.attrs.data.sceneChildNodeInfoList[idx].parmData" class="input" @input="()=>{}">
                      </div>
                      <img class="del" src="@/assets/img/sub.png" alt="" srcset="" @click="del(idx)">
                    </div>
                  </template>
                </template>
                <div class="btn-add">
                  <img src="@/assets/img/add.png" alt="" srcset="" @click="addInfoList">
                </div>
              </template>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <Transition>
      <div v-if="configIsShow" id="_v07whnsy" tabindex="-1" class="config">
        <i class="el-icon-close close1" @click="configIsShow=false" />
        <NodeConfiguration />
      </div>
    </Transition>

    <el-dialog title="生成场景" :visible.sync="dialogFormVisible" width="600px" :modal="false">
      <el-form ref="ruleForm" :model="nodeForm" label-width="100px">
        <el-form-item prop="sceneName" label="场景名称" :rules="[ { required: true, message: '请输入场景名称', trigger: 'blur' }]">
          <el-input
            v-model="nodeForm.sceneName"
            placeholder="请输入"
            style="width: 250px"
          />
        </el-form-item>
        <el-form-item prop="sceneDesc" label="场景描述">
          <el-input
            v-model="nodeForm.sceneDesc"
            placeholder="请输入"
            style="width: 250px"
          />
        </el-form-item>
      </el-form>

      <div class="center">
        <el-button
          class="confirm"
          type="primary"
          @click="submit"
        >提交</el-button>
        <el-button
          class="cancel"
          @click="dialogFormVisible = false"
        >返回</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

// import { FlowChart } from '@/components/FlowChart/index.js'
import { createFD } from '@/components/FlowDraw/index.js'
// import ColorPicker from '@/components/ColorPicker.vue'
import NodeConfiguration from './NodeConfiguration'
import { addScene, getParmListByDeviceIdOrInstrumentId } from '@/api/form'
import { getOperateDataByType } from '@/api/dict'
import { getDeviceList, getMachineList, getComdListByDeviceIdOrInstrumentId } from '@/api/table'

export default {
  name: 'ProcessDesign',
  components: {
    NodeConfiguration
  },
  data() {
    return {
      activeName: 'first',
      nodes: {},
      colorIsShow: false,
      configIsShow: false,
      dialogFormVisible: false,
      nodeForm: {},
      dict: [],
      devicelist: [],
      machinelist: [],
      /** 指令options */
      instructionDict: [],
      dType: '1', // 1. 设备 2. 仪器
      /** 当前激活的绘图工具 */
      toolActive: '',
      /** 参数配置选择项 */
      parameterOptions: []
    }
  },
  computed: {
    colors: {
      get() {
        return {
          hex: this.nodes.color
        }
      },
      set(v) {
        this.nodes.color = v.hex
        this.flowChart.update(this.nodes)
      }

    }
  },
  watch: {
    nodes: {
      handler(val) {
        console.log('val', val)
      },
      deep: false
    }
  },
  mounted() {
    this.getNodeType()
    const fd = createFD('_5mf79t1q')
    fd.onCurrentShapeFn = (node) => {
      console.log('node', node)
      this.nodes = node || {}
    }
    fd.onToolActiveFn = (tool) => {
      this.toolActive = tool
    }
    this.fd = fd
  },
  methods: {

    handleClick(tab, event) {
      console.log(tab, event)
    },
    inputW(e, k) {
      const w = e.target.value.replace(/[^0-9]/g, '')
      const fn = new Function('obj', 'val', ` obj.${k}=val; return obj`)
      this.nodes = fn(this.nodes, Number(w))
      this.flowChart.update(this.nodes)
    },
    inputWord(e, k) {
      const fn = new Function('obj', 'val', ` obj.${k}=val; return obj`)
      this.nodes = fn(this.nodes, e.target.value)
      // this.flowChart.update(this.nodes)
      this.fd.update(this.nodes)
    },
    focusColor() {
      this.colorIsShow = true
    },
    openCinfig() {
      this.configIsShow = true
    },
    generate() {
      this.dialogFormVisible = true
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          /** @type { [any[],Function] } */
          const [n, jsonStr] = this.fd.generate()

          const sceneParentNodeManagerList = n.map((item, idx) => {
            return {
              nodeName: item.attrs.data.txt,
              nodeSort: idx,
              nodeId: item.attrs.id,
              sceneChildNodeManagerList: item.attrs.children?.map((it, index) => {
                const o = {
                  ...it.attrs.data,
                  childNodeName: it.attrs.data.txt,
                  nodeSort: index,
                  nodeId: it.attrs.id
                }
                delete o.txt
                return o
              })
            }
          })
          console.log('result:', sceneParentNodeManagerList)

          const data = {
            ...this.nodeForm,
            nodeJson: jsonStr,
            sceneParentNodeManagerList
          }

          console.log('data', data)

          addScene(data).then(res => {
            if (res.code === 200) {
              this.dialogFormVisible = false
              this.$message.success('添加成功')
              this.fd.clear()
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getNodeType() {
      getOperateDataByType().then((res) => {
        console.log('节点类型', res)
        this.dict = res.data
      })
      getDeviceList({
        pageSize: 1000,
        pageNum: 1
      }).then((res) => {
        this.devicelist = res.rows
      })
      getMachineList({
        pageSize: 1000,
        pageNum: 1
      }).then((res) => {
        this.machinelist = res.rows
      })
    },
    chooseTool(i) {
      this.toolActive = i
      this.fd.toolActive = i
    },
    /** 获取指令列表 */
    getOrder(id) {
      console.log('dictCode:', id)
      const obj = {}
      switch (this.dType) {
        case '1':
          obj.deviceId = id
          break
        case '2':
          obj.instrumentId = id
          break
      }
      this.instructionDict = []
      this.parameterOptions = []
      getComdListByDeviceIdOrInstrumentId(obj).then(res => {
        console.log('res:指令', res)
        if (res.code == 200) {
          this.instructionDict = res.data
        }
      })
      getParmListByDeviceIdOrInstrumentId(obj).then(res => {
        console.log('res:参数', res)
        if (res.code == 200) {
          this.parameterOptions = res.data
        }
      })
    },
    addInfoList() {
      this.nodes.attrs.data.sceneChildNodeInfoList ||= []
      this.nodes.attrs.data.sceneChildNodeInfoList.push({
        parmId: undefined,
        parmData: ''
      })
      console.log('this.nodes:', this.nodes)
      this.nodes = { ...this.nodes }
    },
    del(idx) {
      this.nodes.attrs.data.sceneChildNodeInfoList.splice(idx, 1)
      this.nodes = { ...this.nodes }
    }
  }
}
</script>

<style lang="scss" scoped>
.pd_container {
  position: relative;
  height: calc(100vh - 52px);
  color: #fff;
}
.btn-active {
  img {
    margin-right: 5px;
    vertical-align: bottom;
  }
}
.g1 {
  border-color: rgba(7, 205, 177, 1);
  background-color: rgba(10, 60, 54, 1);
  box-shadow: 0px 0px 10px 0px rgba(7, 205, 177, 1) inset;
}
.top_btn {
  display: flex;
  justify-content: flex-end;
  padding: 10px 20px 14px 0;
}
.body {
  display: grid;
  box-sizing: border-box;
  height: calc(100% - 72px);
  background-color: rgba(0, 194, 255, .1);
  grid-template-columns: 230px 1fr 300px;
  grid-template-rows: 1fr;
  .tools {
    padding: 20px;
    font-size: 14px;
    .item-box {
      display: flex;
      gap: 20px;
    }
    .item-icon {
      display: flex;
      align-items: center;
      flex-direction: column;
      justify-content: center;
      margin: 10px 0;
      gap: 3px;
      &>img {
        height: 32px;
      }
    }
    .active {
      box-shadow: 0px 0px 10px 3px #1298c5;
    }
  }
  .draw {
    position: relative;
    overflow: auto;
    box-sizing: border-box;
    border: 1px solid #157295;
    background-color: #182531;
    &::-webkit-scrollbar {
      width: 0;
      height: 0;
      color: transparent;
    }
  }
}
.allocation {
  .btn {
    padding: 5px 10px;
    cursor: pointer;
    border-radius: 4px;
    background-color: #1d435f;
    box-shadow: #00c2ff 0px 0px 10px 0px inset;
  }
  .input {
    width: 80px;
    height: 22px;
    color: #fff;
    border: 1px solid #7c939d;
    border-radius: 4px;
    outline: none;
    background-color: transparent;
    font-size: 12px;
    caret-color: #fff;
    &:focus {
      border-color: #00c2ff;
    }
  }
  .st1 {
    &>div {
      margin: 8px 16px 8px 10px;
    }
    .bj {
      margin-bottom: 15px;
    }
  }
  .card {
    min-height: 400px;
    .btn-add {
      display: flex;
      align-items: center;
      justify-content: center;
      img {
        width: 20px;
        cursor: pointer;
      }
    }
    .ccon {
      position: relative;
      padding-right: 40px;
      .del {
        position: absolute;
        top: 50%;
        right: 10px;
        width: 20px;
        cursor: pointer;
        transform: translateY(-50%);
      }
    }
  }
  .content1 {
    font-size: 16px;
    &>div {
      display: grid;
      align-items: center;
      justify-items: end;
      grid-template-columns: 75px 1fr;
      &>input {
        width: 100%;
      }
    }
  }
}
::v-deep .el-tabs--top .el-tabs__item.is-top:nth-child(2) {
  padding-left: 38px !important;
}
::v-deep .el-tabs__item.is-active {
  color: #fff !important;
  font-weight: 700 !important;
}
::v-deep .el-tabs__item {
  color: #fff !important;
  font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑', sans-serif !important;
}
::v-deep .el-input__inner {
  height: 22px;
  color: #fff;
  border-color: #7c939d;
  background-color: transparent;
  line-height: 22px;
}
::v-deep .el-input__icon {
  height: auto;
  margin-top: -8px;
}
.config {
  position: absolute;
  z-index: 2;
  top: 0;
  left: 0;
  width: calc(100% - 240px);
  border: 1px solid #157295;
  background-color: #182531;
  // width: 1335px;
  .close1 {
    position: absolute;
    top: 11px;
    right: 17px;
    cursor: pointer;
    color: #909399;
    &:hover {
      color: #409eff;
    }
  }
}
.v-enter-active,
.v-leave-active {
  transition: all 0.2s ease-in-out;
}
.v-enter,
.v-leave-to {
  transform: translateX(-100%);
  opacity: 0;
}
.v-leave,
.v-enter-to {
  transform: translateX(0);
  opacity: 1;
}
</style>
